package com.cimr.comm.controller.manager;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.cimr.comm.bo.MenuBo;
import com.cimr.comm.dto.HttpResult;
import com.cimr.comm.dto.LayuiTableData;
import com.cimr.comm.po.Group;
import com.cimr.comm.po.Role;
import com.cimr.comm.po.User;
import com.cimr.comm.service.GroupService;
import com.cimr.comm.service.MenuService;
import com.cimr.comm.service.RoleService;
import com.cimr.comm.service.UserService;
import com.cimr.comm.token.TokenUtil;
import com.cimr.comm.util.IdUtil;
import com.cimr.dto.ZtreeDto;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by liqi on 2017/12/13.
 * liqiwork@qq.com
 */
@Controller
@RequestMapping("/roleManager/ajax")
public class RoleManagerAjaxController {


    @RequestMapping({"getCurrGroupInfo"})
    @ResponseBody
    public HttpResult getCurrGroupInfo() {
        User user = TokenUtil.getToken();
//        user.getGroupId();
        Role role = new Role();
        role.setGroupId(user.getGroupId());
        role.setGroupName(user.getGroupName());
        HttpResult result = new HttpResult(true, "");
        result.setData(role);
        return result;
    }

//    @RequiresPermissions(value = {"roleManager:getRoleById", "cimrFrame:operation:passkey"}, logical = Logical.OR)
    @RequestMapping({"getRoleById"})
    @ResponseBody
    public HttpResult getRoleById(@RequestParam(required = true) String id) {
        Role role = roleService.getRoleById(id);

        HttpResult result = new HttpResult(true, "");
        result.setData(role);
        return result;
    }

    /**
     *@auther zengfan
     *@date 2018/1/4 10:01
     *@params  * @param null
     *弹出菜单授权表单页需先查询当前角色已授权，然后组装成树形数据
     **/
//    @RequiresPermissions(value = {"roleManager:getMenuPer", "cimrFrame:operation:passkey"}, logical = Logical.OR)
    @RequestMapping({"getMenuZtree"})
    @ResponseBody
    public HttpResult getMenuPer(String id) {
        HttpResult result = new HttpResult(true, "");
        // 获取可选项
        List<MenuBo> allMenuList = menuService.getMenuListByCurrUser();
        // 获取当前已选中的项
        List<MenuBo> curMenuList = menuService.getMenuListByRoleId(id);
        List<ZtreeDto> ztreeList = new ArrayList<ZtreeDto>();
        List<String> idList = new ArrayList<>();
        for (int i = 0;i<allMenuList.size();i++){
            ZtreeDto ztreeDto = new ZtreeDto();
            ztreeDto.setId(allMenuList.get(i).getId());
            ztreeDto.setpId(allMenuList.get(i).getParentId());
            if (allMenuList.get(i).getLevel()==1){
                ztreeDto.setParent(true);
            }
            if (allMenuList.get(i).getLevel()==2){
                ztreeDto.setParent(false);
            }
            ztreeDto.setName(allMenuList.get(i).getMenuName());
            ztreeDto.setChecked(false);
            for (int j=0;j<curMenuList.size();j++){
                if (allMenuList.get(i).getId().equals(curMenuList.get(j).getId())){
                    ztreeDto.setChecked(true);
                    break;
                };
            }
            // 去重
            if (!idList.contains(ztreeDto.getId())) {
                ztreeList.add(ztreeDto);
                idList.add(ztreeDto.getId());
            }
        }
        result.setData(ztreeList);
        return result;
    }

    /**
     *@auther zengfan
     *@date 2018/1/4 14:28
     *@params  * @param null
     *保存菜单配置
     **/
    @RequiresPermissions(value = {"roleManager:save",
                                  "roleManager:saveMenuPer",
                                  "cimrFrame:operation:passkey"}, logical = Logical.OR)
    @RequestMapping({"saveMenuPer"})
    @ResponseBody
    public HttpResult saveMenuPer(String id, String menuIds) {
        int resultStatus1;
        String s = menuIds.substring(1, menuIds.length()-1);
        String[] menuIdsArray=s.split(",");
        for (int i = 0 ;i<menuIdsArray.length;i++){
            menuIdsArray[i]=menuIdsArray[i].substring(1, menuIdsArray[i].length()-1);
        }
        resultStatus1 = roleService.saveRoleAndMenus(id,menuIdsArray);
        HttpResult result = new HttpResult(true, "");
        if(resultStatus1 == 0) {
            result.setSuccess(false);
        }
        return result;
    }

    /**
     *@auther zengfan
     *@date 2018/1/4 14:28
     *@params  * @param null
     *保存操作配置
     **/
    @RequiresPermissions(value = {"roleManager:save",
                                  "roleManager:saveOpationPer",
                                  "cimrFrame:operation:passkey"}, logical = Logical.OR)
    @RequestMapping({"saveOpationPer"})
    @ResponseBody
    public HttpResult saveOpationPer(String id, String ids) {
        String[] idArray = ids.split(",");
        int resultStatus1;
        resultStatus1 = roleService.saveRoleAndOperations(id,idArray);
        HttpResult result = new HttpResult(true, "");
        if(resultStatus1 == 0) {
            result.setSuccess(false);
        }
        return result;
    }

    /**
     *@auther zengfan
     *@date 2018/1/4 14:28
     *@params  * @param null
     *保存角色配置
     **/
    @RequiresPermissions(value = {"roleManager:save",
                                  "roleManager:saveRolePer",
                                  "cimrFrame:operation:passkey"}, logical = Logical.OR)
    @RequestMapping({"saveRolePer"})
    @ResponseBody
    public HttpResult saveRolePer(String id, String ids) {
        int resultStatus1;
        HttpResult result = new HttpResult(true, "");
        if(ids==""||ids==null){
            resultStatus1 = userService.saveUserAndRoles(id,null);
        }else{
            String[] idArray = ids.split(",");
            List<String> idList= new ArrayList<>();
            for(int i=0;i<idArray.length;i++){
                if (idArray[i]!=null){
                    idList.add(idArray[i]);
                }
            }
            String[] roleArray = new String[idList.size()];
            for (int i=0;i<idList.size();i++){
                roleArray[i] = idList.get(i);
            }
            resultStatus1 = userService.saveUserAndRoles(id,roleArray);
            if(resultStatus1 == 0) {
                result.setSuccess(false);
            }
        }
        return result;
    }

//    @RequiresPermissions(value = {"roleManager:getRoleManagerList", "cimrFrame:operation:passkey"}, logical = Logical.OR)
    @RequestMapping({"/getRoleManagerList"})
    @ResponseBody
    public LayuiTableData getRoleManagerList(@RequestParam(required = true,defaultValue = "1") Integer page,
                                             @RequestParam(required = false,defaultValue = "10") Integer limit,
                                             @RequestParam(required = false) String roleName) {

        LayuiTableData result = new LayuiTableData();
        User currentUser = TokenUtil.getToken();
        List<Group> groupList = groupService.getGroupAndSonsByGroupId(currentUser.getGroupId());
        if (groupList!=null && groupList.size()>0) {
            String[] groupIds = new String[groupList.size()];
            for (int i = 0; i < groupList.size(); i++) {
                groupIds[i] = groupList.get(i).getId();
            }
            PageHelper.startPage(page, limit);
            List list = roleService.getRoleListWithName(roleName, groupIds);
            if (list!=null && list.size()>0) {
                PageInfo pageInfo = new PageInfo(list);
                List list1 = roleService.getRoleListWithName(roleName, groupIds);
                result.setCount(list1.size());
                result.setData(pageInfo.getList());
            }
        }
        result.setCode(Integer.valueOf(0));
        result.setMsg("");
        return result;
    }


    @RequiresPermissions(value = {"roleManager:getRolesByUserId", "cimrFrame:operation:passkey"}, logical = Logical.OR)
    @RequestMapping({"getRolesByUserId"})
    @ResponseBody
    public HttpResult getRolesByUserId(@RequestParam(required = true) String id) {
        List<Role> currentList = roleService.getRoleListByUserId(id);
        HttpResult result = new HttpResult(true, "");
        result.setData(currentList);
        return result;
    }

    /**
     * 取角色数据（用于用户管理中的角色穿梭框）
     * @param id 用户id
     * @return
     */
    @RequestMapping({"getRolesTransfer4User"})
    @ResponseBody
    public HttpResult getRolesTransfer4User(@RequestParam(required = true) String id) {
        HttpResult result = new HttpResult(true, "");
        List<Role> haveRoles = roleService.getRoleListByUserId(id);
        JSONArray haveRolesJSONArray = new JSONArray();
        for (int i = 0; i < haveRoles.size(); i++) {
            haveRolesJSONArray.add(haveRoles.get(i).getId());
        }

        User currentUser = TokenUtil.getToken();
        List allRoles = new ArrayList();
        List<Group> groupList = groupService.getGroupAndSonsByGroupId(currentUser.getGroupId());
        if (groupList!=null && groupList.size()>0) {
            String[] groupIds = new String[groupList.size()];
            for (int i = 0; i < groupList.size(); i++) {
                groupIds[i] = groupList.get(i).getId();
            }
            allRoles = roleService.getRoleListWithName("", groupIds);
        }
        JSONArray allRolesJSONArray = new JSONArray();
        for (int i = 0; i < allRoles.size(); i++) {
            JSONObject json = new JSONObject();
            json.put("value", ((Role)allRoles.get(i)).getId());
            json.put("title", ((Role)allRoles.get(i)).getRoleName());
            allRolesJSONArray.add(json);
        }

        Map resultMap = new HashMap();
        resultMap.put("haveRoles", haveRolesJSONArray);
        resultMap.put("allRoles", allRolesJSONArray);
        result.setData(resultMap);
        return result;
    }

    @RequiresPermissions(value = {"roleManager:save",
                                  "roleManager:saveRole",
                                  "cimrFrame:operation:passkey"}, logical = Logical.OR)
    @RequestMapping({"saveRole"})
    @ResponseBody
    public HttpResult saveRole(@RequestParam(required = false) String id,
//                               @RequestParam(required = true) String roleKey,
                               @RequestParam(required = true) String roleName,
                               @RequestParam(required = false) String comment,
                               @RequestParam(required = false) Float orderId,
                               @RequestParam(required = true) String groupId,
                               @RequestParam(required = false) String groupName) {
        int resultStatus = 0;
        if (id!=null && !"".equals(id)) {
            resultStatus = roleService.updateRole(id, null, roleName, comment, orderId, groupId, groupName);
        } else {
            resultStatus = roleService.insertRole(IdUtil.getId()+"", null, roleName, comment, orderId, groupId, groupName);
        }

        HttpResult result = new HttpResult(true, "");
        if (resultStatus==0) {
            result.setSuccess(false);
        }
        return result;
    }

    @RequestMapping({"updateOrderId"})
    @ResponseBody
    public HttpResult updateOrderId(@RequestParam(required = true) String id,
                                    @RequestParam(required = true) Float orderId) {

        int resultStatus = 0;
        resultStatus = roleService.updateOrderId(id, orderId);
        HttpResult result = new HttpResult(true, "");
        if (resultStatus==0) {
            result.setSuccess(false);
        }
        return result;
    }

    @RequiresPermissions(value = {"roleManager:delete",
                                  "roleManager:deleteRole",
                                  "cimrFrame:operation:passkey"}, logical = Logical.OR)
    @RequestMapping({"deleteRole"})
    @ResponseBody
    public HttpResult deleteRole(@RequestParam(required = true) String id) {
        int resultStatus = roleService.deleteRoleById(id);
        HttpResult result = new HttpResult(true, "");
        if(resultStatus == 0) {
            result.setSuccess(false);
        }
        return result;
    }

//    @RequiresPermissions(value = {"roleManager:getRoleListByKey", "cimrFrame:operation:passkey"}, logical = Logical.OR)
    @RequestMapping({"getRoleListByKey"})
    @ResponseBody
    public HttpResult getRoleListByKey(@RequestParam(required = true) String roleKey) {
        List<Role> roleList = roleService.getRoleListByKey(roleKey);
        HttpResult result = new HttpResult(true, "");
        if(roleList!=null){
            if(roleList.size()==0){
                result.setData(null);
            }else{
                result.setData(roleList);
            }
        }
        return result;
    }

    @Autowired
    private RoleService roleService;
    @Autowired
    private MenuService menuService;
    @Autowired
    private UserService userService;
    @Autowired
    private GroupService groupService;
}
